package io.renren.modules.demo.controller;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.dao.DishDao;
import io.renren.common.dto.CategoryDTO;
import io.renren.common.dto.DishDTO;
import io.renren.common.entity.DishFlavorEntity;
import io.renren.common.redis.RedisKeys;

import io.renren.common.redis.RedisUtils;
import io.renren.modules.oss.service.SysOssService;
import io.renren.common.page.PageData;
import io.renren.common.service.CategoryService;
import io.renren.common.service.DishFlavorService;
import io.renren.common.service.DishService;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;

import io.renren.modules.demo.excel.DishExcel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 菜品管理
 *
 * @author yidian ${email}
 * @since 1.0.0 2022-11-06
 */
@RestController
@RequestMapping("demo/dish")
@Api(tags="菜品管理")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SysOssService sysOssService;

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("demo:dish:page")
    @Transactional(rollbackFor = Exception.class)
    @Cacheable(value = "dishPageCache",key = "'dish_'+#params.get('limit')+'_'+#params.get('page')")
    public Result<PageData<DishDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){

        PageData<DishDTO> page =dishService.page(params);
        List<DishDTO> list = page.getList();
        List<DishDTO> dtoList = list.stream().map(item -> {
            // 获取categoryId
            Long categoryId = item.getCategoryId();
            getByWithCategory(item,categoryId);
            // 当前菜品ID
            Long dishId = item.getId();
            dishService.getByWithFlavor(item,dishId);
            return item;
        }).collect(Collectors.toList());
                 page.setList(dtoList);
        return new Result<PageData<DishDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("demo:dish:info")
    @Cacheable(value = "dishCache",key = "'dish_'+#id")
    @Transactional(rollbackFor = Exception.class)
    public Result<DishDTO> get(@PathVariable("id") Long id){
        DishDTO dishDTO = dishService.get(id);
        getByWithCategory(dishDTO,dishDTO.getCategoryId());
        dishService.getByWithFlavor(dishDTO,id);
        return new Result<DishDTO>().ok(dishDTO);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("demo:dish:save")
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(value = "dishPageCache",allEntries = true),
            @CacheEvict(value = "dishflavorPageCache",allEntries = true)
    })
    public Result save(@RequestBody DishDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dishService.save(dto);
        List<DishFlavorEntity> dishFlavors = dto.getDishFlavors();
        dishFlavors.stream().map(item -> {
            Long id = dto.getId();
            item.setDishId(id);
            dishFlavorService.insert(item);
           return item;
        }).collect(Collectors.toList());

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("demo:dish:update")
    @Transactional(rollbackFor = Exception.class)
   @Caching(evict = {
           @CacheEvict(value = "dishCache",key = "'dish_'+#dto.getId()"),
           @CacheEvict(value = "dishPageCache",allEntries = true),
           @CacheEvict(value = "dishflavorPageCache",allEntries = true)
   })
    public Result update(@RequestBody DishDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        //更新前删除表中之前存储的图片数据（判断图片是否更改）
        DishDTO dishDTO = dishService.get(dto.getId());
        if (dishDTO.getImage()!=dto.getImage()){
            sysOssService.deleteByKey(dishDTO.getImage());
        }

        List<DishFlavorEntity> dishFlavors = dto.getDishFlavors();
        dishFlavors.stream().map(item -> {
            Long id = dto.getId();
            item.setDishId(id);
            if (item.getId()==null){
                dishFlavorService.insert(item);
            }else {
                dishFlavorService.updateById(item);
            }
            return item;
        }).collect(Collectors.toList());

        dishService.update(dto);

        return new Result();
    }

    @PutMapping("/updateStatus/{status}")
    @ApiOperation("修改状态")
    @LogOperation("修改状态")
    @RequiresPermissions("demo:dish:update")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "dishPageCache",allEntries = true)
    public Result updateStatus(@PathVariable("status") Integer status, @RequestBody Long[] id){
        //效验数据
        AssertUtils.isArrayEmpty(id, "id");
        for (Long aLong : id) {
            redisUtils.delete(RedisKeys.getDishCacheKey()+"::dish_"+aLong);
            DishDTO dishDTO = dishService.get(aLong);
            dishDTO.setStatus(status);
            dishService.update(dishDTO);
        }
        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("demo:dish:delete")
    @Transactional(rollbackFor = Exception.class)
    @Caching(evict = {
            @CacheEvict(value = "dishPageCache",allEntries = true),
            @CacheEvict(value = "dishflavorPageCache",allEntries = true)
    })
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        dishFlavorService.deleteByDishId(ids);
        //同步删除云存储图片
        for (Long id : ids) {
            DishDTO dishDTO = dishService.get(id);
            sysOssService.deleteByKey(dishDTO.getImage());
            redisUtils.delete(RedisKeys.getDishCacheKey()+"::dish_"+id);
        }
        dishService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("demo:dish:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<DishDTO> list = dishService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, DishExcel.class);
    }

    @GetMapping("list")
    @ApiOperation("查看菜品")
    @RequiresPermissions("demo:dish:list")
    @Cacheable(value = "dishPageCache",key = "'dish_'+'list'")
    public Result<List<DishDTO>> listResult(){
        List<DishDTO> list = dishService.list();
                list.stream().map(item -> {
            // 获取categoryId
            Long categoryId = item.getCategoryId();
            getByWithCategory(item,categoryId);
            // 当前菜品ID
            Long dishId = item.getId();
            dishService.getByWithFlavor(item,dishId);
            return item;
        }).collect(Collectors.toList());



        return new Result<List<DishDTO>>().ok(list);
    }



    /**
     * 提取方法dish获得分类信息
     * @param dishDTO
     * @param categoryId
     */
    public void getByWithCategory(DishDTO dishDTO, Long categoryId) {
        // 给categoryName赋值
        CategoryDTO categoryDTO = categoryService.get(categoryId);
        if(categoryDTO!=null){
            String name = categoryDTO.getName();
            dishDTO.setCategoryName(name);
        }
    }

}